<!-- 文档的弹出框事件 -->
<template>
  <div class="docDialog">
    <div
      v-if="isDialog.isShow"
      class="modleDialog"
    />
    <el-dialog
      :visible.sync="isDialog.isShow"
      :before-close="closeDialog"
      :modal="false"
      :top="isDialog.top || '25vh'"
      width="40%"
    >
      <!-- 头部参数 -->
      <div slot="title">
        <!-- 新建文件夹, 修改文件名称 -->
        <div v-if="['add', 'edit', 'admin', 'record', 'directory', 'repeat'].includes(isDialog.docEntr)">
          <span
            v-if="isDialog.docEntr == 'directory' || isDialog.docEntr == 'repeat'"
            class="title"
          >提示</span>
          <span
            v-if="isDialog.docEntr == 'add'"
            class="title"
          >新建文件夹</span>
          <span
            v-if="isDialog.docEntr == 'edit'"
            class="title"
          >修改文件名称</span>
          <span
            v-if="isDialog.docEntr == 'record'"
            class="title"
          >操作记录</span>
          <span
            v-if="isDialog.docEntr == 'admin'"
            class="title"
          >设置权限</span>
          <span v-if="['add', 'edit'].includes(isDialog.docEntr)">（ 文件名称限定50字 ）</span>
        </div>
        <!-- 下载 分享 -->
        <div v-if="['downLoad','remove', 'share', 'recovery', 'noRole'].includes(isDialog.docEntr)">
          <div class="title">
            <i class="jeicon jeicon-question-circle blueFontQuestion" />
            <span class="blueFont font16">{{ isDialog.docEntr == 'share' && `分享记录 (${
              isDialog.shareNames.length}人)` || '消 息' }}</span>
          </div>
        </div>
      </div>
      <!-- 主要内容 -->
      <div class="main">
        <!-- 新建文件夹 -->
        <div v-if="['add', 'edit'].includes(isDialog.docEntr)">
          <el-row>
            <el-col
              :span="3"
            >
              <span>文件夹名称</span>
            </el-col>
            <el-col
              :span="20"
              :offset="1"
            >
              <el-input
                v-model.trim="addInput"
                :show-word-limit="isIE9m"
                autofocus
                maxlength="50"
                clearable
                placeholder="文件的名称"
                class="filename-input"
              />
            </el-col>
          </el-row>
        </div>
        <div
          v-if="['repeat'].includes(isDialog.docEntr)"
          class="textCenter font18"
        >
          {{ isDialog.roleData }}请重新选择再次上传
        </div>
        <!-- 文件权限不足的提示 -->
        <div
          v-if="['noRole'].includes(isDialog.docEntr)"
          class="textCenter font18"
        >
          <span>文件名为：“</span>
          <span
            v-for="(role, _role) in isDialog.roleData.data"
            :key="_role"
          >{{ role.name }}<span v-if="_role != isDialog.roleData.data.length - 1">，</span></span>
          <span>” 您不具备 “<span class="blueFont">{{ isDialog.roleData.roleTitle }}</span>”的权限，请重新选择。</span>
        </div>
        <!-- 下载、删除和回收站恢复 -->
        <div v-if="['downLoad','remove', 'recovery','directory', 'repeat'].includes(isDialog.docEntr)">
          <div class="textCenter fontBold">
            <span
              v-if="isDialog.docEntr == 'downLoad'"
            >确认文件下载？</span>
            <span
              v-if="isDialog.docEntr == 'directory'"
            >该版本仅支持上传3层目录结构，请修改后重新上传</span>
            <span
              v-if="isDialog.docEntr == 'recovery'"
            >你确定要恢复该文件吗？</span>
            <span
              v-if="isDialog.docEntr == 'remove'"
            >{{ isDialog.removeAll ? `你确定要${isDialog.removeAll}` :'确定删除文件吗？' }}</span>
          </div>
        </div>
        <div v-if="['copy','move', 'receive'].includes(isDialog.docEntr)">
          <div
            v-if="isDialog.docEntr == 'copy'"
            class="title-operate"
          >
            复制
          </div>
          <div
            v-if="isDialog.docEntr == 'move'"
            class="title-operate"
          >
            移动到
          </div>
          <div
            v-if="isDialog.docEntr == 'receive'"
            class="title-operate"
          >
            转存
          </div>
          <div style="max-height: 400px;overflow: auto;">
            <tree
              :child-list="treeList"
              :widthDialog="'100%'"
            />
          </div>
        </div>
        <!-- 设置权限或者操作记录 -->
        <companyDialog
          :dialogObj="{isDialog, checkData}"
          v-if="['admin', 'record'].includes(isDialog.docEntr)"
          @checkDataList="checkDataList"
        />
      </div>
      <!-- 弹框页脚 确认取消按钮 -->
      <div
        v-if="isDialog.docEntr != 'share'"
        class="footer"
      >
        <el-row
          :type="isIe"
          justify="center"
        >
          <el-col
            :span="3"
            v-if="['add', 'edit', 'remove', 'copy', 'move', 'receive', 'recovery', 'admin', 'directory', 'repeat'].includes(isDialog.docEntr)"
          >
            <el-button
              @click="addDoc(isDialog.docEntr, addInput)"
              class="whiteFont buttonBg font12"
            >
              确认
            </el-button>
          </el-col>
          <el-col
            :span="3"
            :offset="1"
            v-if="['add', 'edit', 'remove', 'copy', 'move', 'receive', 'recovery', 'admin'].includes(isDialog.docEntr)"
          >
            <el-button
              @click="closeDialog"
              class="blackFont buttonColseBg font12"
            >
              取消
            </el-button>
          </el-col>
        </el-row>
        <!-- 下载 -->
        <el-row
          v-if="isDialog.docEntr == 'downLoad'"
          :type="isIe"
          justify="center"
        >
          <!-- <el-col :span="5">
            <el-button
              @click="downLoadSub('no')"
              class="whiteFont buttonBg font12"
            >
              不，依旧下载
            </el-button>
          </el-col> -->
          <el-col
            :span="3"
          >
            <el-button
              @click="downLoadSub"
              class="whiteFont buttonBg font12"
            >
              下载
            </el-button>
          </el-col>
          <el-col
            :span="3"
            :offset="1"
          >
            <el-button
              @click="closeDialog"
              class="blackFont buttonColseBg font12"
            >
              取消
            </el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 分享的主要显示 -->
      <div class="shareNamesMain">
        <el-tag
          v-for="(share, shareIndex) in isDialog.shareNames"
          :key="shareIndex"
          class="ml-10"
        >
          <span>
            {{ share }}
          </span>
        </el-tag>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import List from '../../../controllers/list/listController';
import Accept from '../../../controllers/list/acceptController';
import Recovery from '../../../controllers/list/recoveryController';
import { getArrStyle, getAssignKeyData } from '../../../common/util';
import { removeUtilt } from '../../../common/dialog';
import Tree from '../../../components/tree';
import { EventBus } from '../../../common/eventBus';
// 公司弹框的组件
import companyDialog from './company';

export default {

  components: { Tree, companyDialog },
  props: {
    isDialog: {
      type: Object,
      default: () => {},
    },
    getMenu: {
      type: Object,
      default: () => {},
    },
    nodeId: {
      type: Number,
      default: null,
    },
    // 父组件选中的数据
    checkData: {
      type: Array,
      default: () => [],
    },
    // 父组件当前列表的所有数据
    mainList: {
      type: Array,
      default: null,
    },
  },
  data() {
    return {
      addInput: '', // 新建文件的输入框
      list: new List(),
      accept: new Accept(),
      recovery: new Recovery(),
      routerNow: '1-1', // 当前点击左侧菜单对吧
      menuData: {}, // 父组件传递过来的参数
      initNodIds: [], // 格式化父组件的nodeID
      changeMainList: [], // 执行过添加或者删除列表数据之后的mainList
      treeList: [], // 文件夹的列表
      targetId: null,
      loadingSub: null, // 加载动画
      checkList: [], // 公司选中的数据
      companyId: null, // 点击权限设置对应 的ID
      isIE9m: false,
    };
  },
  computed: {
    isIe() {
      return window.performance && ('msDoNotTrack' in window.navigator) ? 'inline-block' : 'flex';
    },
    diskType() {
      let diskType = 'self';
      if (this.menuData.router == '1-1') {
        diskType = 'company';
      }
      if (this.menuData.router == '1-2') {
        diskType = 'self';
      }
      return diskType;
    },
  },
  watch: {
    isDialog: {
      handler(nv) {
        // 如果是修改文件名称
        if (nv.docEntr == 'edit') {
          this.addInput = nv.inputData.type ? nv.inputData.name.substring(0, nv.inputData.name.indexOf('.')) : nv.inputData.name;
        } else {
          this.addInput = '';
        }
        this.getPropsData(nv);
      },
      deep: true,
    },
  },
  created() {
    if (Ext.isIE9m) {
      this.isIE9m = true;
    }
  },
  mounted() {
    // this.getPropsData(); // 初始化父组件的数据
    EventBus.$on('NOW_OBJ', async (target) => {
      this.targetId = target.obj.nodeId;
      // this.params.nodeType = 'dir';
    });
  },
  beforeDestroy() {
  },
  methods: {
    // 获取公司文件权限的数据
    checkDataList(datas, nodeId) {
      this.companyId = nodeId;
      this.checkList = [];
      datas.forEach((item) => {
        if (item.checkTitle == '全公司') {
          item.type = 'company';
          this.checkList.push(item);
        }
        if (item.data.length) {
          item.data.forEach(((ele) => {
            ele.check && this.checkList.push(ele);
          }));
        }
      });
    },
    // 关闭弹框方法
    closeDialog() {
      this.$emit('clsoeDialog', 'close');
      this.addInput = ''; // 让新建的输入框为空
      this.initNodIds.length = 0; // 让当前选中的数据为空
      EventBus.$emit('closeDialog', {
        status: 'close',
      });
      this.isDialog.isShow = false;
      // this.loadingSub.close(); // 关闭加载动画loading
    },
    // 判断当前显示的内容
    getPropsData() {
      this.menuData = this.getMenu;// 父组件的菜单参数
      if (!this.menuData) return;
      this.routerNow = this.menuData.routerText || 'self'; // 判断company的原因：因为默认第一次进来routerText是获取不到的，默认显示为company
      let key = '';
      if (this.menuData.router == '1-1' || this.menuData.router == '1-2') {
        key = 'nodeId';
      } else {
        key = 'id';
      }
      this.initNodIds = getArrStyle(key, this.checkData); // 获取数组中对应字段的数据
      if (['copy', 'move', 'receive'].includes(this.isDialog.docEntr)) {
        this.getDirList();
      }
    },
    downLoadSub() {
      // this.loadingSub = this.$loading({
      //   lock: true,
      //   text: '',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(255, 255, 255, 0.7)',
      // });
      // if (type == 'no') {
      //   this.initNodIds.forEach((nodeIds) => {
      //     this.list.skyDriveDownLoad(nodeIds);
      //   });
      // } else {
      //   this.list.skyDriveDownLoad(this.initNodIds.join(','));
      // }
      this.list.skyDriveDownLoad(this.initNodIds.join(','), this.diskType);
      // 执行完上面操作之后关闭弹出框
      this.closeDialog();
      this.$emit('changeMainList', {
        data: null,
        status: 'download',
      });
    },
    // 获取文件夹
    async getDirList() {
      const param = {
        diskType: this.routerNow,
        order: JSON.stringify([{ code: 'time', type: 'desc' }]),
        nodeType: 'dir',
        parentId: null,
        tag: '',
        suffix: '',
        key: '',
      };
      const list = {
        name: '全部文件',
        diskType: this.routerNow,
        type: null,
        nodeId: '',
        parent: '',
        open: true,
        source: 'copy',
      };
      const res = await this.list.initList(param);
      // if (!res.length) {
      //   JE.msg('没有文件夹可选哦，快去新建吧~');
      //   return false;
      // }
      const itemRes = res.map((item) => {
        item.open = false;
        item.source = 'copy';
        return { ...item };
      });
      list.children = itemRes;
      this.$set(this.treeList, 0, list);
    },
    formatParams(role, type) {
      const res = this.checkList.filter(item => item.role == role && item.type == type);
      if (!res.length) return false;
      const ids = [];
      const names = [];
      const obj = {};
      res.forEach((item) => {
        ids.push(item.id);
        names.push(item.name);
      });
      obj.role = role;
      obj.type = type;
      obj.code = ids.join(',');
      obj.name = names.join(',');
      return obj;
    },
    // 点击确认按钮
    async addDoc(text, input) {
      if (text == 'admin') {
        const params = [];
        const roleList = ['manage', 'edit', 'download', 'check'];
        const limtList = ['company', 'branch', 'dept', 'role', 'staff'];
        roleList.map((roleItem) => {
          limtList.map((limtItem) => {
            const res = this.formatParams(roleItem, limtItem);
            res && params.push(res);
          });
        });
        this.list.setPowerFile(this.companyId, params);
        this.closeDialog();
        return false;
      }
      this.loadingSub = this.$loading({
        lock: true,
        text: '',
        spinner: 'el-icon-loading',
        background: 'rgba(149, 149, 149, 0.1)',
      });
      if (text == 'directory' || text == 'repeat') {
        this.loadingSub.close();
        setTimeout(() => {
          this.closeDialog();
        }, 500);
        return false;
      }
      // 点击新建
      if (text == 'add') {
        if (!input.match('^[a-zA-Z0-9_\u4e00-\u9fa5]+$')) {
          this.loadingSub.close(); // 关闭加载动画loading
          JE.msg('内容只能输入数字、字母、汉字~');
          return false;
        }
        const res = await this.list.addFolder(this.nodeId, input, this.routerNow);
        this.loadingSub.close(); // 关闭加载动画loading
        if (!res) return;

        this.mainList.unshift(res);
        this.$emit('changeMainList', {
          data: this.mainList,
          status: 'no',
        });
      }
      // 点击编辑
      if (text == 'edit') {
        const editData = this.isDialog.inputData;
        const type = editData.type ? `.${editData.type}` : '';
        if (!this.addInput.match('^[a-zA-Z0-9_\u4e00-\u9fa5]+$')) {
          this.loadingSub.close(); // 关闭加载动画loading
          JE.msg('内容只能输入数字、字母、汉字~');
          return false;
        }
        const inputVal = `${this.addInput}${type}`;
        // 这边做的一个操作就是修改的时候显示的是除了后缀之后的内容；为了防止修改胡乱后缀造成不必要的问题
        const res = await this.list.editFile(editData.diskType, inputVal, editData.nodeId);
        this.loadingSub.close(); // 关闭加载动画loading
        if (!res) return;
        this.isDialog.inputData.name = inputVal;
        this.mainList = this.mainList.filter((file) => {
          if (file.nodeId == editData.nodeId) {
            return this.isDialog.inputData;
          }
          return file;
        });
      }
      // 删除的方法
      if (text == 'remove') {
        if (this.menuData.router == '2') {
          this.loadingSub.close(); // 关闭加载动画loading
          this.$emit('changeMainList', {
            data: this.mainList,
            status: 'remove',
          });
          return;
        }
        const removeData = await removeUtilt(this.initNodIds, this.menuData, this.mainList);
        this.loadingSub.close(); // 关闭加载动画loading
        this.$emit('changeMainList', {
          data: removeData,
          status: 'remove',
        });
      }
      if (text == 'copy') {
        let diskType = '';
        if (this.menuData.router == '1-1') {
          diskType = 'company';
        } else if (this.menuData.router == '1-2') {
          diskType = 'self';
        }
        const res = await this.list.filesCopy(this.initNodIds, this.targetId, diskType);
        this.loadingSub.close(); // 关闭加载动画loading
        if (!res) return false;
        if (this.targetId == this.nodeId) {
          this.mainList.unshift(res);
          this.$emit('changeMainList', {
            data: this.mainList,
            status: 'move',
          });
        } else {
          this.$emit('changeMainList', {
            data: this.mainList,
            status: 'move',
          });
        }
      }

      if (text == 'move') {
        // let diskType = '';
        // if (this.menuData.router == '1-1') {
        //   diskType = 'company';
        // } else if (this.menuData.router == '1-2') {
        //   diskType = 'self';
        // }
        const res = await this.list.filesMove(this.initNodIds, this.targetId, this.diskType);
        this.loadingSub.close(); // 关闭加载动画loading
        if (!res) return false;
        const newlist = getAssignKeyData('nodeId', this.initNodIds, this.mainList);
        this.$emit('changeMainList', {
          data: newlist,
          status: 'move',
        });
      }
      // 转存
      if (text == 'receive') {
        const res = await this.accept.shareDocTransfer(this.initNodIds[0], this.targetId, this.diskType);
        const newlist = getAssignKeyData('id', this.initNodIds, this.mainList);
        this.loadingSub.close(); // 关闭加载动画loading
        this.showNotify(res, '转存文件成功', '转存文件失败，请稍后尝试', { data: newlist, status: 'no' });
      }
      // 回收站恢复
      if (text == 'recovery') {
        // JE.msg('回收站恢复功能暂未对接');
        const res = await this.recovery.recoveryFile(this.initNodIds[0], this.diskType);
        const newlist = getAssignKeyData('id', this.initNodIds, this.mainList);
        this.loadingSub.close(); // 关闭加载动画loading
        this.showNotify(res, '文件已恢复', '文件恢复失败，请稍后尝试', { data: newlist, status: 'no' });
      }
      // 执行完上面操作之后关闭弹出框
      this.closeDialog();
    },
    // 文件执行的弹框
    showNotify(res, title, noTitle, changeList) {
      if (res) {
        this.$notify({
          title: '成功',
          message: title,
          type: 'success',
        });
        this.$emit('changeMainList', {
          data: changeList.data || null,
          status: changeList.status,
        });
      } else {
        this.$notify({
          title: '失败',
          message: noTitle,
          type: 'error',
        });
      }
    },
  },
};

</script>
<style lang='scss' scoped>
</style>
<style lang='scss'>
  @import './index.scss';
</style>
